#!/bin/bash
# Author: fanyongfeng
# 安装postgresql-11
# 操作系统：centos7/银河麒麟v10

set -e
# 使用root用户执行
[[ $(id -u) -ne 0 ]] && echo "请使用root用户执行此脚本" && exit 1

# 设置临时环境变量
VERSION="15.6"
INSTALL_DIR="/data/pgsql/15"
DATA_DIR="${INSTALL_DIR}/data"
RUN_USER="postgres"
HOST_IP=$(ip a | grep global | head -1 | awk -F'/' '{print $1}' | awk '{print $2}')

# 下载安装包
[[ -f postgresql-${VERSION}.tar.gz ]] || wget https://ftp.postgresql.org/pub/source/v${VERSION}/postgresql-${VERSION}.tar.gz
if [[ $? -ne 0 ]]
then
    echo "postgresql-${VERSION}.tar.gz下载失败，请重试或手动上传此安装包"
    exit 1
fi

# 关闭防火墙和selinux
systemctl stop firewalld && systemctl disable firewalld
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
setenforce  0
 
# 安装依赖
yum -y install gcc gcc-c++ bzip2 gzip zip unzip openssl openssl-devel zlib-devel zlib readline-devel readline libxml2-devel libxslt-devel uuid-devel systemd-devel
 
# 编译安装
mkdir -p  ${INSTALL_DIR} ${DATA_DIR}

echo "正在解压文件：postgresql-${VERSION}.tar.gz"
tar zxf postgresql-${VERSION}.tar.gz && cd postgresql-${VERSION}
./configure --prefix=${INSTALL_DIR}  --with-openssl --with-libxml --with-libxslt --with-ossp-uuid --with-systemd
CPU_NUMBER=$(cat /proc/cpuinfo |grep processor | wc -l)
gmake -j ${CPU_NUMBER} world
gmake install-world
 
# 添加用户、修改权限
useradd ${RUN_USER}
chown -R ${RUN_USER}.${RUN_USER} ${INSTALL_DIR} ${DATA_DIR}
 
# 初始化数据
su - ${RUN_USER} -c "${INSTALL_DIR}/bin/initdb -D ${DATA_DIR} --encoding=UTF8 --lc-collate=en_US.UTF-8 --lc-ctype=en_US.UTF-8"
 
# 添加环境变量
cat > /etc/profile.d/postgresql.sh <<EOF
export PATH=\$PATH:${INSTALL_DIR}/bin
EOF
source /etc/profile
 
# systemd 管理
cat > /etc/systemd/system/postgresql.service << EOF
[Unit]
Description=PostgreSQL 15 database server
Documentation=https://www.postgresql.org/docs/15/static/
After=syslog.target
After=network.target
 
[Service]
Type=notify
 
User=${RUN_USER}
Group=${RUN_USER}
 
# Note: avoid inserting whitespace in these Environment= lines, or you may
# break postgresql-setup.
 
# Location of database directory
Environment=PGDATA=${DATA_DIR}
 
# Where to send early-startup messages from the server (before the logging
# options of postgresql.conf take effect)
# This is normally controlled by the global default set by systemd
# StandardOutput=syslog
 
# Disable OOM kill on the postmaster
OOMScoreAdjust=-1000
Environment=PG_OOM_ADJUST_FILE=/proc/self/oom_score_adj
Environment=PG_OOM_ADJUST_VALUE=0
 
ExecStart=${INSTALL_DIR}/bin/postmaster -D \${PGDATA}
ExecReload=/bin/kill -HUP \$MAINPID
KillMode=mixed
KillSignal=SIGINT
  
# Do not set any timeout value, so that systemd will not kill postmaster
# during crash recovery.
TimeoutSec=0
 
# 0 is the same as infinity, but "infinity" needs systemd 229
TimeoutStartSec=0
 
TimeoutStopSec=1h
 
[Install]
WantedBy=multi-user.target
EOF
 
 
# 启动服务
systemctl daemon-reload
systemctl enable postgresql
systemctl start postgresql
sleep 2
systemctl status postgresql